package org.dei.perla.sys.dbutils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import org.dei.perla.sys.core.PerlaRuntime;

public class PerlaCalibrationLoader {

	private static String queryBegin	= "SELECT COEFFICIENT, C_INDEX FROM ";
	private static String queryEnd		= " WHERE NODE_ID = ? AND DATA_SOURCE_ID = ? ORDER BY C_INDEX; ";
	private static String queryEndS		= " WHERE NODE_NAME = ? AND DATA_SOURCE_NAME = ? ORDER BY C_INDEX; ";

	
//	private static PreparedStatement statement;
	
	
	public static Double[] getCoefficient(int nodeID, int dataSourceID) throws PerlaCalibrationLoaderException, SQLException{
		String tablename = PerlaRuntime.getDefaultRuntime().getProperty("PERLA_CALIBRATION_TABLE");
		if(tablename != null){
			return getCoefficients(tablename, nodeID, dataSourceID);
		}
		else{
			throw new PerlaCalibrationLoaderException();			
		}
	}

	public static Double[] getCoefficient(String nodeName, String dataSourceName) throws PerlaCalibrationLoaderException, SQLException{
		String tablename = PerlaRuntime.getDefaultRuntime().getProperty("PERLA_CALIBRATION_TABLE").toLowerCase() + "view";
		if(tablename != null){
			return getCoefficients(tablename, nodeName, dataSourceName);
		}
		else{
			throw new PerlaCalibrationLoaderException();			
		}
	}
	
	private static Double[] getCoefficients(String tablename, int nodeID, int dataSourceID) throws SQLException{
		PreparedStatement statement = PerlaSQLExec.createPreparedStatementInternal(queryBegin + tablename + queryEnd);
		statement.setInt(1, nodeID);
		statement.setInt(2, dataSourceID);
		ArrayList<Double> arrayList = new ArrayList<Double>();
		PerlaSQLExec.fetchColumnValues("COEFFICIENT", statement, arrayList);
		return arrayList.toArray(new Double[arrayList.size()]);
	}

	private static Double[] getCoefficients(String tablename, String pDeviceName, String fieldName) throws SQLException {
		PreparedStatement statement = PerlaSQLExec.createPreparedStatementInternal(queryBegin + tablename + queryEndS);
		statement.setString(1, pDeviceName);
		statement.setString(2, fieldName);
		ArrayList<Double> arrayList = new ArrayList<Double>();
		PerlaSQLExec.fetchColumnValues("COEFFICIENT", statement, arrayList);
		return arrayList.toArray(new Double[arrayList.size()]);
	}
	
}
